<template>
  <div class="operation-log-management">
    <div class="page-header">
      <h2>操作日志管理</h2>
      <div class="header-actions">
        <el-button 
          v-if="hasPermission('admin:log:clean')"
          type="danger" 
          @click="showCleanDialog"
        >
          <el-icon><Delete /></el-icon>
          清理日志
        </el-button>
        <el-button 
          v-if="hasPermission('admin:log:export')"
          type="success" 
          @click="exportLogs"
        >
          <el-icon><Download /></el-icon>
          导出日志
        </el-button>
      </div>
    </div>

    <!-- 查询条件 -->
    <div class="search-form">
      <el-form :model="queryForm" inline>
        <el-form-item label="用户名">
          <el-input v-model="queryForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="操作模块">
          <el-select v-model="queryForm.module" placeholder="请选择模块" clearable>
            <el-option label="用户管理" value="用户管理" />
            <el-option label="角色管理" value="角色管理" />
            <el-option label="权限管理" value="权限管理" />
            <el-option label="菜单管理" value="菜单管理" />
            <el-option label="个人中心" value="个人中心" />
            <el-option label="系统登录" value="系统登录" />
            <el-option label="日志管理" value="日志管理" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select v-model="queryForm.operationType" placeholder="请选择操作类型" clearable>
            <el-option label="新增" value="CREATE" />
            <el-option label="修改" value="UPDATE" />
            <el-option label="删除" value="DELETE" />
            <el-option label="查询" value="QUERY" />
            <el-option label="登录" value="LOGIN" />
            <el-option label="登出" value="LOGOUT" />
            <el-option label="导出" value="EXPORT" />
            <el-option label="导入" value="IMPORT" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态" clearable>
            <el-option label="成功" value="SUCCESS" />
            <el-option label="失败" value="FAILURE" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleDateRangeChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchLogs">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="table-actions">
      <el-button 
        v-if="hasPermission('admin:log:delete')"
        type="danger" 
        :disabled="selectedLogs.length === 0"
        @click="batchDeleteLogs"
      >
        <el-icon><Delete /></el-icon>
        批量删除
      </el-button>
      <span class="selected-info" v-if="selectedLogs.length > 0">
        已选择 {{ selectedLogs.length }} 条记录
      </span>
    </div>

    <!-- 日志表格 -->
    <div class="table-container">
      <el-table 
        :data="logs" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="username" label="用户名" width="100" />
        <el-table-column prop="nickname" label="用户昵称" width="100" />
        <el-table-column prop="module" label="操作模块" width="120" />
        <el-table-column prop="operationTypeDesc" label="操作类型" width="100" />
        <el-table-column prop="operationDesc" label="操作描述" width="150" show-overflow-tooltip />
        <el-table-column prop="statusDesc" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 'SUCCESS' ? 'success' : 'danger'">
              {{ row.statusDesc }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="executionTime" label="执行时间" width="100">
          <template #default="{ row }">
            {{ row.executionTime }}ms
          </template>
        </el-table-column>
        <el-table-column prop="ipAddress" label="IP地址" width="120" />
        <el-table-column prop="location" label="地点" width="100" />
        <el-table-column prop="createTimeStr" label="操作时间" width="160" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="hasPermission('admin:log:view')"
              type="primary" 
              size="small" 
              @click="viewLogDetail(row)"
            >
              详情
            </el-button>
            <el-button 
              v-if="hasPermission('admin:log:delete')"
              type="danger" 
              size="small" 
              @click="deleteLog(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryForm.page"
        v-model:page-size="queryForm.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 日志详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="操作日志详情" width="80%">
      <div v-if="currentLogDetail" class="log-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户信息">
            {{ currentLogDetail.nickname }}({{ currentLogDetail.username }})
          </el-descriptions-item>
          <el-descriptions-item label="操作模块">
            {{ currentLogDetail.module }}
          </el-descriptions-item>
          <el-descriptions-item label="操作类型">
            {{ currentLogDetail.operationType }}
          </el-descriptions-item>
          <el-descriptions-item label="操作描述">
            {{ currentLogDetail.operationDesc }}
          </el-descriptions-item>
          <el-descriptions-item label="请求方法">
            {{ currentLogDetail.requestMethod }}
          </el-descriptions-item>
          <el-descriptions-item label="请求URL">
            {{ currentLogDetail.requestUrl }}
          </el-descriptions-item>
          <el-descriptions-item label="操作状态">
            <el-tag :type="currentLogDetail.status === 'SUCCESS' ? 'success' : 'danger'">
              {{ currentLogDetail.status === 'SUCCESS' ? '成功' : '失败' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="执行时间">
            {{ currentLogDetail.executionTime }}ms
          </el-descriptions-item>
          <el-descriptions-item label="IP地址">
            {{ currentLogDetail.ipAddress }}
          </el-descriptions-item>
          <el-descriptions-item label="操作地点">
            {{ currentLogDetail.location }}
          </el-descriptions-item>
          <el-descriptions-item label="操作时间">
            {{ currentLogDetail.createTime }}
          </el-descriptions-item>
          <el-descriptions-item label="业务类型">
            {{ currentLogDetail.businessType }}
          </el-descriptions-item>
        </el-descriptions>
        
        <div v-if="currentLogDetail.requestParams" class="detail-section">
          <h4>请求参数</h4>
          <el-input
            v-model="currentLogDetail.requestParams"
            type="textarea"
            :rows="4"
            readonly
          />
        </div>
        
        <div v-if="currentLogDetail.responseResult" class="detail-section">
          <h4>响应结果</h4>
          <el-input
            v-model="currentLogDetail.responseResult"
            type="textarea"
            :rows="4"
            readonly
          />
        </div>
        
        <div v-if="currentLogDetail.errorMsg" class="detail-section">
          <h4>错误信息</h4>
          <el-input
            v-model="currentLogDetail.errorMsg"
            type="textarea"
            :rows="3"
            readonly
          />
        </div>
        
        <div v-if="currentLogDetail.userAgent" class="detail-section">
          <h4>用户代理</h4>
          <el-input
            v-model="currentLogDetail.userAgent"
            type="textarea"
            :rows="2"
            readonly
          />
        </div>
      </div>
    </el-dialog>

    <!-- 清理日志对话框 -->
    <el-dialog v-model="cleanDialogVisible" title="清理历史日志" width="400px">
      <el-form :model="cleanForm" label-width="120px">
        <el-form-item label="保留天数">
          <el-input-number 
            v-model="cleanForm.days" 
            :min="1" 
            :max="365"
            placeholder="请输入保留天数"
          />
          <div class="form-tip">将删除 {{ cleanForm.days }} 天前的所有日志</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cleanDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmCleanLogs" :loading="cleanLoading">
          确认清理
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Delete, Download } from '@element-plus/icons-vue'
import request from '../utils/request'
import { usePermissions } from '../stores/permission'

const { hasPermission } = usePermissions()

const logs = ref([])
const loading = ref(false)
const total = ref(0)
const selectedLogs = ref([])
const detailDialogVisible = ref(false)
const currentLogDetail = ref(null)
const cleanDialogVisible = ref(false)
const cleanLoading = ref(false)
const dateRange = ref([])

const queryForm = reactive({
  page: 1,
  size: 20,
  username: '',
  module: '',
  operationType: '',
  status: '',
  startTime: '',
  endTime: ''
})

const cleanForm = reactive({
  days: 30
})

// 获取操作日志列表
const fetchLogs = async () => {
  try {
    loading.value = true
    const response = await request.post('/operation-log/page', queryForm)
    logs.value = response.data.list
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('获取操作日志失败')
  } finally {
    loading.value = false
  }
}

// 搜索日志
const searchLogs = () => {
  queryForm.page = 1
  fetchLogs()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(queryForm, {
    page: 1,
    size: 20,
    username: '',
    module: '',
    operationType: '',
    status: '',
    startTime: '',
    endTime: ''
  })
  dateRange.value = []
  fetchLogs()
}

// 处理时间范围变化
const handleDateRangeChange = (value) => {
  if (value && value.length === 2) {
    queryForm.startTime = value[0]
    queryForm.endTime = value[1]
  } else {
    queryForm.startTime = ''
    queryForm.endTime = ''
  }
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedLogs.value = selection
}

// 查看日志详情
const viewLogDetail = async (row) => {
  try {
    const response = await request.get(`/operation-log/${row.id}`)
    currentLogDetail.value = response.data
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取日志详情失败')
  }
}

// 删除单个日志
const deleteLog = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条操作日志吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await request.delete(`/operation-log/${row.id}`)
    ElMessage.success('删除成功')
    fetchLogs()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除日志
const batchDeleteLogs = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedLogs.value.length} 条操作日志吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const ids = selectedLogs.value.map(log => log.id)
    await request.delete('/operation-log/batch', { data: ids })
    ElMessage.success('批量删除成功')
    fetchLogs()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 显示清理对话框
const showCleanDialog = () => {
  cleanDialogVisible.value = true
}

// 确认清理日志
const confirmCleanLogs = async () => {
  try {
    cleanLoading.value = true
    const response = await request.post(`/operation-log/clean?days=${cleanForm.days}`)
    ElMessage.success(`成功清理了 ${response.data} 条历史日志`)
    cleanDialogVisible.value = false
    fetchLogs()
  } catch (error) {
    ElMessage.error('清理日志失败')
  } finally {
    cleanLoading.value = false
  }
}

// 导出日志
const exportLogs = async () => {
  try {
    ElMessage.info('导出功能开发中...')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 分页处理
const handleSizeChange = (size) => {
  queryForm.size = size
  queryForm.page = 1
  fetchLogs()
}

const handleCurrentChange = (page) => {
  queryForm.page = page
  fetchLogs()
}

onMounted(() => {
  fetchLogs()
})
</script>

<style scoped>
.operation-log-management {
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e6e6e6;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.table-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.selected-info {
  color: #606266;
  font-size: 14px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
}

.log-detail {
  max-height: 600px;
  overflow-y: auto;
}

.detail-section {
  margin-top: 20px;
}

.detail-section h4 {
  margin-bottom: 10px;
  color: #333;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style>
